import 'package:flutter_test/flutter_test.dart';
import 'package:awak/common/models/topic.dart';
import 'package:awak/common/models/content.dart';
import 'package:awak/common/models/user.dart';
import 'package:awak/common/models/review.dart';
import 'package:awak/page/community/topic_data_holder.dart';
import 'package:awak/page/community/content_data_holder.dart';

void main() {
  group('Detail Topic Page Improvements Tests', () {
    late Topic testTopic;
    late List<Content> testContents;
    late List<User> testUsers;
    late List<Review> testReviews;

    setUp(() {
      // 重置状态
      TopicDataHolder.setCurrentTopic(null);
      ContentDataHolder.clearCurrentContent();
      ContentDataHolder.allContents.clear();

      // 创建测试主题
      testTopic = Topic(
        id: 1,
        title: 'Philosophy and Deep Thinking',
        label: 'Philosophy',
        content: 'Explore the depths of philosophical thought',
        coverImage: 'philosophy.jpg',
        numberPeople: 150,
        userId: 1,
      );

      // 创建测试用户
      testUsers = [
        User(
          id: 1,
          username: 'alpha',
          password: 'password',
          nickname: 'Alpha User',
          avatar: 'avatar1.jpg',
          signature: 'Philosophy enthusiast',
        ),
        User(
          id: 2,
          username: 'bravo',
          password: 'password',
          nickname: 'Bravo User',
          avatar: 'avatar2.jpg',
          signature: 'Deep thinker',
        ),
        User(
          id: 3,
          username: 'charlie',
          password: 'password',
          nickname: 'Charlie User',
          avatar: 'avatar3.jpg',
          signature: 'Wisdom seeker',
        ),
      ];

      // 创建测试内容
      testContents = [
        Content(
          id: 1,
          picture: 'content1.jpg',
          description: 'First philosophical content with many reviews',
          userId: 2,
          topicId: 1,
          publishedAt: DateTime.now().subtract(Duration(hours: 1)),
        ),
        Content(
          id: 2,
          picture: 'content2.jpg',
          description: 'Second philosophical content with few reviews',
          userId: 3,
          topicId: 1,
          publishedAt: DateTime.now().subtract(Duration(hours: 2)),
        ),
        Content(
          id: 3,
          picture: 'content3.jpg',
          description: 'Third philosophical content with no reviews',
          userId: 2,
          topicId: 1,
          publishedAt: DateTime.now().subtract(Duration(hours: 3)),
        ),
      ];

      // 创建测试评论
      testReviews = [
        // content1 有 5 条评论
        Review(id: 1, content: 'Great philosophical insight!', userId: 1, contentId: 1),
        Review(id: 2, content: 'Very thought-provoking', userId: 3, contentId: 1),
        Review(id: 3, content: 'Thanks for sharing this wisdom', userId: 2, contentId: 1),
        Review(id: 4, content: 'Interesting perspective on life', userId: 1, contentId: 1),
        Review(id: 5, content: 'Well articulated thoughts', userId: 3, contentId: 1),
        
        // content2 有 2 条评论
        Review(id: 6, content: 'Nice philosophical post', userId: 1, contentId: 2),
        Review(id: 7, content: 'Good point about existence', userId: 2, contentId: 2),
        
        // content3 有 0 条评论
      ];

      TopicDataHolder.setCurrentTopic(testTopic);
      ContentDataHolder.allContents = testContents;
    });

    test('should handle content click navigation to detail page', () {
      // 测试content点击导航逻辑
      final content = testContents[0];
      
      // 模拟点击content
      ContentDataHolder.setCurrentContent(content);
      
      // 验证导航状态
      expect(ContentDataHolder.currentContent, isNotNull);
      expect(ContentDataHolder.currentContent?.id, 1);
      expect(ContentDataHolder.currentContent?.description, contains('philosophical'));
      
      // 验证可以获取完整的content数据
      final currentContent = ContentDataHolder.currentContent!;
      expect(currentContent.picture.isNotEmpty, true);
      expect(currentContent.userId, greaterThan(0));
      expect(currentContent.topicId, testTopic.id);
    });

    test('should calculate review counts correctly for topic contents', () {
      // 计算每个content的评论数量
      final reviewCounts = <int, int>{};
      for (final review in testReviews) {
        reviewCounts[review.contentId] = (reviewCounts[review.contentId] ?? 0) + 1;
      }
      
      // 验证评论数量计算正确
      expect(reviewCounts[1], 5); // content1 有5条评论
      expect(reviewCounts[2], 2); // content2 有2条评论
      expect(reviewCounts[3] ?? 0, 0); // content3 有0条评论
      
      // 验证总评论数
      final totalReviews = reviewCounts.values.fold(0, (sum, count) => sum + count);
      expect(totalReviews, testReviews.length);
    });

    test('should identify top reviewer user correctly', () {
      // 模拟获取评论数最多的用户逻辑
      final reviewCounts = <int, int>{};
      for (final review in testReviews) {
        reviewCounts[review.contentId] = (reviewCounts[review.contentId] ?? 0) + 1;
      }
      
      // 统计每个用户的总评论数（基于content的评论数量）
      Map<int, int> userReviewCounts = {};
      for (final content in testContents) {
        final contentReviewCount = reviewCounts[content.id] ?? 0;
        if (contentReviewCount > 0) {
          userReviewCounts[content.userId] = (userReviewCounts[content.userId] ?? 0) + contentReviewCount;
        }
      }
      
      // 移除当前用户（假设为用户1）
      userReviewCounts.remove(1);
      
      if (userReviewCounts.isNotEmpty) {
        // 找到评论最多的用户ID
        int topUserId = userReviewCounts.entries
            .reduce((a, b) => a.value > b.value ? a : b)
            .key;
        
        // 验证结果
        expect(topUserId, 2); // 用户2应该是评论最多的（content1有5条评论 + content3有0条评论）
        
        // 获取用户信息
        final topUser = testUsers.where((u) => u.id == topUserId).firstOrNull;
        expect(topUser, isNotNull);
        expect(topUser?.nickname, 'Bravo User');
      }
    });

    test('should handle no recommended users scenario', () {
      // 测试没有推荐用户的场景
      
      // 创建一个没有评论的主题
      final emptyTopic = Topic(
        id: 2,
        title: 'Empty Topic',
        label: 'Empty',
        content: 'Topic with no content or reviews',
        coverImage: 'empty.jpg',
        numberPeople: 0,
        userId: 1,
      );
      
      TopicDataHolder.setCurrentTopic(emptyTopic);
      
      // 空的内容列表
      final emptyContents = <Content>[];
      
      // 验证没有推荐用户的情况
      expect(emptyContents.isEmpty, true);
      
      // 模拟获取top reviewer的逻辑
      Map<int, int> userReviewCounts = {};
      for (final content in emptyContents) {
        // 空列表，不会执行
      }
      
      userReviewCounts.remove(1); // 移除当前用户
      
      expect(userReviewCounts.isEmpty, true);
      // 应该显示 "No recommended users available"
    });

    test('should support content-topic relationship in detail view', () {
      // 验证详情页面中content与topic的关系
      for (final content in testContents) {
        expect(content.topicId, testTopic.id);
        expect(content.userId, anyOf(2, 3)); // 内容由用户2或3创建
      }
      
      // 验证topic数据完整性
      expect(testTopic.title.isNotEmpty, true);
      expect(testTopic.label.isNotEmpty, true);
      expect(testTopic.content.isNotEmpty, true);
      expect(testTopic.numberPeople, greaterThan(0));
    });

    test('should handle review count display formatting', () {
      // 测试评论数量显示格式
      final reviewCounts = <int, int>{};
      for (final review in testReviews) {
        reviewCounts[review.contentId] = (reviewCounts[review.contentId] ?? 0) + 1;
      }
      
      // 验证不同数量的显示格式
      expect('${reviewCounts[1]}', '5'); // 5条评论
      expect('${reviewCounts[2]}', '2'); // 2条评论
      expect('${reviewCounts[3] ?? 0}', '0'); // 0条评论
      
      // 验证数字范围
      expect(reviewCounts[1], greaterThan(0));
      expect(reviewCounts[2], greaterThan(0));
      expect(reviewCounts[3] ?? 0, equals(0));
    });

    test('should maintain data consistency across navigation', () {
      // 验证导航过程中的数据一致性
      
      // 1. 设置主题
      TopicDataHolder.setCurrentTopic(testTopic);
      expect(TopicDataHolder.currentTopic?.id, testTopic.id);
      
      // 2. 点击content导航
      final content = testContents[0];
      ContentDataHolder.setCurrentContent(content);
      
      // 3. 验证数据一致性
      expect(ContentDataHolder.currentContent?.topicId, testTopic.id);
      expect(ContentDataHolder.currentContent?.id, content.id);
      
      // 4. 验证可以获取相关数据
      final relatedReviews = testReviews.where((r) => r.contentId == content.id).toList();
      expect(relatedReviews.isNotEmpty, true);
      expect(relatedReviews.length, 5);
    });

    test('should support user information display', () {
      // 验证用户信息显示
      for (final user in testUsers) {
        expect(user.nickname?.isNotEmpty ?? false, true);
        expect(user.username.isNotEmpty, true);
        expect(user.avatar?.isNotEmpty ?? false, true);
        expect(user.signature?.isNotEmpty ?? false, true);
      }
      
      // 验证用户与content的关联
      for (final content in testContents) {
        final author = testUsers.where((u) => u.id == content.userId).firstOrNull;
        expect(author, isNotNull);
      }
    });

    test('should handle edge cases in top reviewer calculation', () {
      // 测试top reviewer计算的边界情况
      
      // 1. 所有用户都是当前用户的情况
      final singleUserContents = [
        Content(
          id: 4,
          picture: 'content4.jpg',
          description: 'Content by current user',
          userId: 1, // 当前用户
          topicId: 1,
          publishedAt: DateTime.now(),
        ),
      ];
      
      Map<int, int> userReviewCounts = {};
      userReviewCounts[1] = 10; // 当前用户有很多评论
      
      // 移除当前用户
      userReviewCounts.remove(1);
      
      expect(userReviewCounts.isEmpty, true);
      
      // 2. 多个用户评论数量相同的情况
      userReviewCounts = {2: 5, 3: 5}; // 两个用户评论数量相同
      
      final topUserId = userReviewCounts.entries
          .reduce((a, b) => a.value > b.value ? a : b)
          .key;
      
      expect([2, 3].contains(topUserId), true); // 应该是其中一个
    });

    test('should validate UI component data requirements', () {
      // 验证UI组件的数据需求
      
      // 1. Content卡片数据需求
      for (final content in testContents) {
        expect(content.picture.isNotEmpty, true); // 图片路径
        expect(content.description.isNotEmpty, true); // 描述文本
        expect(content.publishedAt, isNotNull); // 发布时间
      }
      
      // 2. 用户信息数据需求
      for (final user in testUsers) {
        expect(user.id, greaterThan(0)); // 用户ID
        expect(user.username.isNotEmpty, true); // 用户名
        // nickname和avatar可以为空，会有默认值
      }
      
      // 3. 评论数据需求
      for (final review in testReviews) {
        expect(review.contentId, greaterThan(0)); // 关联的content ID
        expect(review.userId, greaterThan(0)); // 评论者ID
        expect(review.content.isNotEmpty, true); // 评论内容
      }
    });
  });
}
